package com.baihejia.common.dubbo.server.libs;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class IP {

    public static String getPublicIP() {
        try {
            String ip = "";
            String chinaz = "http://ip.chinaz.com";

            StringBuilder inputLine = new StringBuilder();
            String read;
            URL url;
            HttpURLConnection urlConnection;
            BufferedReader in = null;
            try {
                url = new URL(chinaz);
                urlConnection = (HttpURLConnection) url.openConnection();
                in = new BufferedReader( new InputStreamReader(urlConnection.getInputStream(),"UTF-8"));
                while((read=in.readLine())!=null){
                    inputLine.append(read).append("\r\n");
                }
            } finally{
                if(in!=null){
                    try {
                        in.close();
                    } catch (IOException ignored) {
                    }
                }
            }

            Pattern p = Pattern.compile("\\<dd class\\=\"fz24\">(.*?)\\<\\/dd>");
            Matcher m = p.matcher(inputLine.toString());
            if(m.find()){
                ip = m.group(1);
            }
            return ip;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}